package com.boken.caelum.common.manager;

import com.boken.caelum.common.mybatis.mapper.Mapper;
import com.boken.caelum.common.mybatis.model.ModelExample;
import com.github.pagehelper.PageHelper;

import java.util.Collections;
import java.util.List;


public abstract class ManagerImpl<M, E extends ModelExample> implements Manager<M, E> {

	protected Mapper<M, E> mapper;

	@Override
	public Long countByExample(E example) {
		return mapper.countByExample(example);
	}

	@Override
	public Long deleteByExample(E example) {
		return mapper.deleteByExample(example);
	}

	@Override
	public Long deleteByPrimaryKey(Object id) {
		return mapper.deleteByPrimaryKey(id);
	}

	@Override
	public Long insert(M model) {
		Long flag = mapper.insert(model);
		return flag;
	}

	@Override
	public Long insertSelective(M model) {
		Long flag = mapper.insertSelective(model);
		return flag;
	}

	@Override
	public List<M> selectByExample(E example) {
		List<M> list = mapper.selectByExample(example);
		if (list == null) {
			list = Collections.emptyList();
		}
		return list;
	}

	@Override
	public M selectByPrimaryKey(Object id) {
		return mapper.selectByPrimaryKey(id);
	}

	@Override
	public M selectOneByExample(E example) {
		example.setLimit(1);
		example.setOffset(0);
		List<M> list = selectByExample(example);
		if (list.size() > 0) {
			return list.get(0);
		}
		return null;
	}

	@Override
	public Long updateByExampleSelective(M model, E example) {
		return mapper.updateByExampleSelective(model, example);
	}

	@Override
	public Long updateByPrimaryKeySelective(M model) {
		return mapper.updateByPrimaryKeySelective(model);
	}

	@Override
	public Long updateByExample(M model, E example) {
		return mapper.updateByExample(model, example);
	}

	@Override
	public Long updateByPrimaryKey(M model) {
		return mapper.updateByPrimaryKey(model);
	}

	@Override
	public M insertAndGetId(M model){
		mapper.insertAndGetId(model);
		return model;
	}
	@Override
	public List<M> selectPageByExample(Integer pageNum, Integer pageSize, E example){
		pageNum = pageNum == null ? 1 : pageNum;
		pageSize = pageSize == null ? 10 : pageSize;
		PageHelper.startPage(pageNum, pageSize);
		List<M> list = selectByExample(example);
		return list;
	}
}
